package models.parsers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import models.BankStatement;
import models.Transaction;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

public class HsbcDebitParser extends BaseExcelParser {
    static Logger _logger = Logger.getLogger(HsbcCreditParser.class);
    private static final int COLUMN_DATE = 3;

    public HsbcDebitParser(String filename) {
        super(filename);
    }

    public boolean parse() {
        setAlreadyParsed(false);
        try {
            workbook = readFile();

            HSSFSheet sheet = workbook.getSheetAt(0);
            List<Transaction> transactions = getTransactionsFromSheet(sheet);
            BankStatement statment = new BankStatement(transactions);
            setStatement(statment);
            setAlreadyParsed(true);
        } catch (IOException e) {
            _logger.error(e);
        }
        return alreadyParsed();
    }

    List<Transaction> getTransactionsFromSheet(HSSFSheet sheet) {
        List<Transaction> transactions = new ArrayList<Transaction>();

        int rows = sheet.getLastRowNum();
        int initRow = findTransactionsHeaderRow(sheet);
        for (int r = initRow + 1; r < rows; r++) {
            HSSFRow row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            String dateString = getStringValue(row.getCell(COLUMN_DATE));
            String label = getStringValue(row.getCell(COLUMN_DATE + 1));
            String charge = getStringValue(row.getCell(COLUMN_DATE + 2));
            String deposit = getStringValue(row.getCell(COLUMN_DATE + 3));

            if (StringUtils.isBlank(dateString) && StringUtils.isBlank(label) && StringUtils.isBlank(charge) && StringUtils.isBlank(deposit)) {
                break;
            }

            String amountString = deposit;
            if (StringUtils.isNotBlank(charge)) {
                amountString = "-" + charge;
            }
            transactions.add(new Transaction(null, null, parseDate(dateString), label, parseAmount(amountString)));
        }

        return transactions;
    }

    @Override
    public int findTransactionsHeaderRow(HSSFSheet sheet) {
        return findRowWithText(sheet, "Fecha");
    }
}
